package com.question.business.user.repository.impl;

import com.question.business.user.model.dto.UserCacheDTO;
import com.question.business.user.repository.IUserCacheRepository;
import com.question.business.user.service.IUserService;
import com.question.common.constants.RedisConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 用户缓存Repository实现类
 *
 * @author star
 * @since 2023/9/7
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserCacheRepositoryImpl implements IUserCacheRepository {

    private IUserService userService;

    private RedisTemplate redisTemplate;

    /**
     * 根据用户ID查询缓存
     *
     * @param userId 用户ID
     * @return UserCacheDTO
     */
    @Override
    public UserCacheDTO queryById(String userId) {
        HashOperations<String, String, UserCacheDTO> ops = redisTemplate.opsForHash();
        return ops.get(RedisConstants.USER_CACHE, userId);
    }

    /**
     * 用户缓存初始化
     */
    @Override
    public void initCache() {
        log.info("用户缓存初始化开始");
        Map<String, UserCacheDTO> map = userService.queryUserCache();
        HashOperations<String, String, UserCacheDTO> ops = redisTemplate.opsForHash();
        ops.putAll(RedisConstants.USER_CACHE, map);
        log.info("用户缓存初始化结束");
    }

}
